﻿using PolePositionMobile.Entities;
using PolePositionMobile.Logic;
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlServerCe;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace PolePositionMobile
{
    /// <summary>
    /// The starting screen of the application, with a list of the visits in the database
    /// </summary>
    public partial class frmHomePage : frmBase
    {
        //Created by: VMCoder
        //Creation date: -
        //Last updated by: VMCoder
        //Last update: 2008.04.15

        public frmHomePage()
        {
            InitializeComponent();
        }

        protected void frmHomePage_Load(object sender, EventArgs e)
        {
            #region Config form
            lblTitle.Text = "Pole Position Mobile | Home";
            lblLButtonText.Text = "New";
            lblRButtonText.Text = "Menu";
            lblLButton.ContextMenu = menLButton;
            LButtonMenuXOffset = 1;
            LButtonMenuYOffset = 59;//40;
            lblRButton.ContextMenu = menRButton;
            RButtonMenuXOffset = 4;
            RButtonMenuYOffset = 116;//97;
            #endregion
            FillGrid();
        }
        private void FillGrid()
        {

            grdVisits.RowHeadersVisible = false;
            grdVisits.DataSource = LogicLayer.GetGridData();
            #region Set grid styles
            DataGridTableStyle _GridTableStyle = new DataGridTableStyle();
            DataGridTextBoxColumn _DGCol;
            #region VisitId
            _DGCol = new DataGridTextBoxColumn();
            _DGCol.MappingName = "VisitId";
            _DGCol.Width = 0;
            _GridTableStyle.GridColumnStyles.Add(_DGCol);
            #endregion
            #region Top
            _DGCol = new DataGridTextBoxColumn();
            _DGCol.MappingName = "TopName";
            _DGCol.HeaderText = "Top";
            _GridTableStyle.GridColumnStyles.Add(_DGCol);
            #endregion
            #region Poles
            _DGCol = new DataGridTextBoxColumn();
            _DGCol.MappingName = "Poles";
            _DGCol.HeaderText = "Poles";
            _DGCol.Width = 65;
            _GridTableStyle.GridColumnStyles.Add(_DGCol);
            #endregion
            #region Images
            _DGCol = new DataGridTextBoxColumn();
            _DGCol.MappingName = "Images";
            _DGCol.HeaderText = "Images";
            _DGCol.Width = 65;
            _GridTableStyle.GridColumnStyles.Add(_DGCol);
            #endregion
            //#region OrderTime
            //_DGCol = new DataGridTextBoxColumn();
            //_DGCol.MappingName = "OrderTime";
            //_DGCol.Width = 0;
            //_GridTableStyle.GridColumnStyles.Add(_DGCol);
            //#endregion
            #region Time
            _DGCol = new DataGridTextBoxColumn();
            _DGCol.MappingName = "Time";
            _DGCol.HeaderText = "Time";
            _GridTableStyle.GridColumnStyles.Add(_DGCol);
            #endregion
            grdVisits.TableStyles.Add(_GridTableStyle);
            #endregion
        }

        private void Duplicate(Int32 visitId)
        {
            //Int32 _I, _J;
            //EImage _Image;
            ShowLoading();
            Application.DoEvents();
            DeleteTempFiles();
            EVisit _Visit = LogicLayer.LoadCompleteVisit(visitId);
            #region Reset Ids
            #region This code should be used in case of wanting to duplicate images
            //for (_I = 0; _I < _Visit.Images.Length; _I++)
            //{
            //    _Image = _Visit.Images[_I];
            //    _Image.ImageId = Int32.MinValue;
            //    if (!String.IsNullOrEmpty(_Image.Filename) && File.Exists(PPIConstants.K_ImagesFolder + _Image.Filename))
            //        File.Copy(PPIConstants.K_ImagesFolder + _Image.Filename, PPIConstants.K_ImagesFolder + "temp_" + _I.ToString() + ".jpeg");
            //    _Image.Filename = "temp_" + _I.ToString() + ".jpeg";
            //    if (_Image.PoleFk != Int32.MinValue)
            //    {
            //        _J = 0;
            //        while(_J < _Visit.Data.Poles.Length && _Visit.Data.Poles[_J].PoleId != _Image.PoleFk)
            //            _J++;
            //        _Image.PoleFk = _Visit.Data.Poles[_J].PoleId == _Image.PoleFk ? _J : Int32.MinValue;
            //        _Image.PoleFkIsId = false;
            //    }
            //}
            #endregion
            _Visit.Images = new EImage[0];
            foreach (EPole _Pole in _Visit.Data.Poles)
                _Pole.PoleId = Int32.MinValue;
            _Visit.Data.DataId = Int32.MinValue;
            _Visit.VisitId = Int32.MinValue;
            #endregion
            ResetSolution(_Visit);
        }

        private void mitNew_Click(object sender, EventArgs e)
        {
            ShowLoading();
            Application.DoEvents();
            DeleteTempFiles();
            ResetSolution(new EVisit());
        }
        private void mitDuplicate_Click(object sender, EventArgs e)
        {
            if (grdVisits.CurrentRowIndex > -1)
            {
                Duplicate(Utils.ToInt32(grdVisits[grdVisits.CurrentRowIndex, 0]));
            }
        }
        private void mitDuplicateLast_Click(object sender, EventArgs e)
        {
            if (grdVisits.VisibleRowCount > 0)
            {
                Int32 _LastVisitId = -1;
                for (Int32 _I = 0; _I < grdVisits.VisibleRowCount; _I++)
                    if (_LastVisitId < Utils.ToInt32(grdVisits[grdVisits.CurrentRowIndex, 0]))
                        _LastVisitId = Utils.ToInt32(grdVisits[grdVisits.CurrentRowIndex, 0]);
                if (_LastVisitId > -1)
                    Duplicate(_LastVisitId);
            }
            else
                mitNew_Click(sender, e);
        }
        private void mitAddImage_Click(object sender, EventArgs e)
        {
            if (grdVisits.CurrentRowIndex > -1)
            {
                ShowLoading();
                Application.DoEvents();
                DeleteTempFiles();
                EVisit _Visit = LogicLayer.LoadCompleteVisit(Utils.ToInt32(grdVisits[grdVisits.CurrentRowIndex, 0]));
                frmPhotos _Form = new frmPhotos();
                _Form.Visit = _Visit;
                _Form.PolesNumber = _Visit.Data.Poles.Length;
                _Form.PhotosNumber = _Visit.Images.Length;
                _Form.EnableTabs = false;
                _Form.Settings = this.Settings;
                _Form.Show();
                this.Hide();
            }
        }
        private void mitEdit_Click(object sender, EventArgs e)
        {
            if (grdVisits.CurrentRowIndex > -1)
            {
                ShowLoading();
                Application.DoEvents();
                DeleteTempFiles();
                EVisit _Visit = LogicLayer.LoadCompleteVisit(Utils.ToInt32(grdVisits[grdVisits.CurrentRowIndex, 0]));
                frmDataCollectionStructure _Form = new frmDataCollectionStructure();
                _Form.Visit = _Visit;
                _Form.PolesNumber = _Visit.Data.Poles.Length;
                _Form.PhotosNumber = _Visit.Images.Length;
                _Form.Settings = this.Settings;
                _Form.Show();
                this.Hide();
            }
        }
        private void mitDelete_Click(object sender, EventArgs e)
        {
            if (grdVisits.CurrentRowIndex > -1 && MessageBox.Show("Are you sure you want to delete visit n°" + (grdVisits.CurrentRowIndex + 1).ToString() + "?", PPIConstants.K_AppName, MessageBoxButtons.YesNo, MessageBoxIcon.None, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                ShowLoading();
                Application.DoEvents();
                LogicLayer.DeleteCompleteVisit(Utils.ToInt32(grdVisits[grdVisits.CurrentRowIndex, 0]));
                FillGrid();
                HideLoading("Pole Position Mobile | Home");
                Application.DoEvents();
            }
        }
        private void mitBackup_Click(object sender, EventArgs e)
        {
            this.Hide();
            SaveFileDialog saveFile = new SaveFileDialog();
            Application.DoEvents();
            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                DirectoryInfo _DestinationDirectory = new DirectoryInfo(saveFile.FileName);

                Application.DoEvents();
                string[] _AppDataFolderFiles = Directory.GetFiles(PPIConstants.K_AppDataFolder);
                string[] _ImagesFolderFiles = Directory.GetFiles(PPIConstants.K_ImagesFolder);
                prgBackup.Maximum = _AppDataFolderFiles.Length + _ImagesFolderFiles.Length;
                prgBackup.Minimum = 0;
                prgBackup.Value = 0;
                lblBackup.Text = "Proccessing...\r\n" + prgBackup.Value.ToString() + " of " + prgBackup.Maximum.ToString();
                pnlBackup.Visible = true;
                pnlBackup.BringToFront();
                Application.DoEvents();
                if (!Directory.Exists(_DestinationDirectory.FullName + Path.DirectorySeparatorChar + PPIConstants.K_BACKUPFOLDERNAME))
                    Directory.CreateDirectory(_DestinationDirectory.FullName + Path.DirectorySeparatorChar + PPIConstants.K_BACKUPFOLDERNAME);

                string _Destination = _DestinationDirectory.FullName + Path.DirectorySeparatorChar + PPIConstants.K_BACKUPFOLDERNAME + Path.DirectorySeparatorChar + DateTime.Now.ToString("yyyyMMddHHmmss") + "\\";
                if (!Directory.Exists(_Destination + "Images\\"))
                    Directory.CreateDirectory(_Destination + "Images\\");
                foreach (string _Element in _AppDataFolderFiles)
                {
                    File.Copy(_Element, _Destination + Path.GetFileName(_Element), true);
                    prgBackup.Value++;
                    lblBackup.Text = "Proccessing...\r\n" + prgBackup.Value.ToString() + " of " + prgBackup.Maximum.ToString();
                    Application.DoEvents();
                }
                foreach (string _Element in _ImagesFolderFiles)
                {
                    File.Copy(_Element, _Destination + "Images\\" + Path.GetFileName(_Element), true);
                    prgBackup.Value++;
                    lblBackup.Text = "Proccessing...\r\n" + prgBackup.Value.ToString() + " of " + prgBackup.Maximum.ToString();
                    Application.DoEvents();
                }

                pnlBackup.Visible = false;
                Application.DoEvents();
                if (MessageBox.Show("Backup done." + Environment.NewLine + "Clear database?", PPIConstants.K_AppName, MessageBoxButtons.YesNo, MessageBoxIcon.None, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    ShowLoading();
                    Application.DoEvents();
                    if (Directory.Exists(PPIConstants.K_ImagesFolder))
                        Directory.Delete(PPIConstants.K_ImagesFolder, true);
                    Directory.CreateDirectory(PPIConstants.K_ImagesFolder);

                    LogicLayer.ClearDatabase();
                    HideLoading("Pole Position Mobile | Home");
                    Application.DoEvents();
                    FillGrid();
                }
            }
            this.Show();
            SetCorrectOrder();
        }
        private void mitSettings_Click(object sender, EventArgs e)
        {
            ShowLoading();
            Application.DoEvents();
            frmSettings _Form = new frmSettings();
            _Form.Settings = this.Settings;
            _Form.Show();
            this.Hide();
        }
        private void mitAbout_Click(object sender, EventArgs e)
        {
            ShowLoading();
            Application.DoEvents();
            frmAboutMobile _Form = new frmAboutMobile();
            _Form.Settings = this.Settings;
            _Form.Show();
            this.Hide();
        }

        private void grdVisits_CurrentCellChanged(object sender, EventArgs e)
        {
            mitDuplicate.Enabled = (grdVisits.CurrentRowIndex > -1);
            mitAddImage.Enabled = (grdVisits.CurrentRowIndex > -1);
            mitEdit.Enabled = (grdVisits.CurrentRowIndex > -1);
            mitDelete.Enabled = (grdVisits.CurrentRowIndex > -1);
            
            //Selecting full Row.
            grdVisits.Select(grdVisits.CurrentRowIndex);
        }

        private void lblHeaderTop_Click(object sender, EventArgs e)
        {
            DataTable _Dt = (DataTable)grdVisits.DataSource;
            ComponentResourceManager resources = new ComponentResourceManager(typeof(frmHomePage));
            pbxHeaderTop.Visible = true;
            pbxHeaderPoles.Visible = false;
            pbxHeaderImages.Visible = false;
            pbxHeaderTime.Visible = false;
            if (_Dt.DefaultView.Sort == "TopName ASC")
            {
                _Dt.DefaultView.Sort = "TopName DESC";
                pbxHeaderTop.Image = (Image)resources.GetObject("downarrow");
            }
            else
            {
                _Dt.DefaultView.Sort = "TopName ASC";
                pbxHeaderTop.Image = (Image)resources.GetObject("uparrow");
            }
        }
        private void lblHeaderPoles_Click(object sender, EventArgs e)
        {
            DataTable _Dt = (DataTable)grdVisits.DataSource;
            ComponentResourceManager resources = new ComponentResourceManager(typeof(frmHomePage));
            pbxHeaderTop.Visible = false;
            pbxHeaderPoles.Visible = true;
            pbxHeaderImages.Visible = false;
            pbxHeaderTime.Visible = false;
            if (_Dt.DefaultView.Sort == "Poles ASC")
            {
                _Dt.DefaultView.Sort = "Poles DESC";
                pbxHeaderPoles.Image = (Image)resources.GetObject("downarrow");
            }
            else
            {
                _Dt.DefaultView.Sort = "Poles ASC";
                pbxHeaderPoles.Image = (Image)resources.GetObject("uparrow");
            }
        }
        private void lblHeaderImages_Click(object sender, EventArgs e)
        {
            DataTable _Dt = (DataTable)grdVisits.DataSource;
            ComponentResourceManager resources = new ComponentResourceManager(typeof(frmHomePage));
            pbxHeaderTop.Visible = false;
            pbxHeaderPoles.Visible = false;
            pbxHeaderImages.Visible = true;
            pbxHeaderTime.Visible = false;
            if (_Dt.DefaultView.Sort == "Images ASC")
            {
                _Dt.DefaultView.Sort = "Images DESC";
                pbxHeaderImages.Image = (Image)resources.GetObject("downarrow");
            }
            else
            {
                _Dt.DefaultView.Sort = "Images ASC";
                pbxHeaderImages.Image = (Image)resources.GetObject("uparrow");
            }
        }
        private void lblHeaderTime_Click(object sender, EventArgs e)
        {
            DataTable _Dt = (DataTable)grdVisits.DataSource;
            ComponentResourceManager resources = new ComponentResourceManager(typeof(frmHomePage));
            pbxHeaderTop.Visible = false;
            pbxHeaderPoles.Visible = false;
            pbxHeaderImages.Visible = false;
            pbxHeaderTime.Visible = true;
            if (_Dt.DefaultView.Sort == "Time ASC")//"OrderTime ASC")
            {
                _Dt.DefaultView.Sort = "Time DESC";//"OrderTime DESC";
                pbxHeaderTime.Image = (Image)resources.GetObject("downarrow");
            }
            else
            {
                _Dt.DefaultView.Sort = "Time ASC";//"OrderTime ASC";
                pbxHeaderTime.Image = (Image)resources.GetObject("uparrow");
            }
        }
    }
}